
package com.wu.shiro;

import com.wu.constants.Constants;
import com.wu.enums.LoginEnum;
import com.wu.enums.UserSessionEnum;
import com.wu.exception.BusinessException;
import com.wu.pojo.dto.SessionUserDto;
import com.wu.service.sys.SResourceService;
import com.wu.service.sys.SUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Set;

/**
 * shiro登录和获取权限信息
 */
public class ShiroRealm extends AuthorizingRealm {
    private final static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

    @Resource
    private SUserService userService;
    @Resource
    private SResourceService resourceService;

    public ShiroRealm() {
        super.setAuthorizationCachingEnabled(true);
        super.setAuthorizationCacheName(Constants.SHIRO_USER_RESOURCES);
    }

    /**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        SessionUserDto sUserDo = (SessionUserDto) SecurityUtils.getSubject().getSession().getAttribute(UserSessionEnum.SESSION_USER_KEY.getKey());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 添加用户权限信息
        Set<String> resourceByUserId = resourceService.getResourceByUserId(sUserDo.getId());
        //获取用户权限集合
        info.setStringPermissions(resourceByUserId);
        return info;
    }

    /**
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        try {
            String userName = token.getUsername();
            SessionUserDto sessionUserDto = userService.getUserDoByUsername(userName);
            if (sessionUserDto == null) {
                throw new BusinessException(LoginEnum.USER_LOGIN_FAIL_USER_PASSWORD_FAIL_MSG);
            }
            Session session = SecurityUtils.getSubject().getSession();
            ByteSource credentialsSalt = ByteSource.Util.bytes(Constants.SALT_CXDY + sessionUserDto.getSalt());
            session.setAttribute(UserSessionEnum.SESSION_USER_KEY.getKey(), sessionUserDto);
            session.setAttribute(UserSessionEnum.SESSION_USER_ID_KEY.getKey(), sessionUserDto.getId());
            return new SimpleAuthenticationInfo(userName, sessionUserDto.getPassword(), credentialsSalt, String.valueOf(sessionUserDto.getId()));
        } catch (Exception e) {
            throw new AuthenticationException("认证出错", e);
        }
    }


}
